package main

import (
	"context"
	"fmt"
	"gin-kitex-gorm/dao"
	user "gin-kitex-gorm/kitex_gen/user"
)

// UsersrvImpl implements the last service interface defined in the IDL.
type UsersrvImpl struct{}

// Register implements the UsersrvImpl interface.
func (s *UsersrvImpl) Register(ctx context.Context, req *user.UserRegisterRequest) (resp *user.UserRegisterResponse, err error) {
	// TODO: Your code here...
	username := req.Username
	password := req.Password

	if len(username) == 0 || len(password) == 0 {
		return &user.UserRegisterResponse{
			StatusCode: -1,
			StatusMsg:  "oops",
			UserId:     0,
			Token:      "",
		}, nil
	}

	userStruct, err := dao.QueryUserByName(username)
	if userStruct == nil && err == nil {
		id := dao.AddUser(username, password)
		return &user.UserRegisterResponse{
			StatusCode: 0,
			StatusMsg:  "",
			UserId:     id,
			Token:      "unknown",
		}, nil
	} else if userStruct != nil {
		return &user.UserRegisterResponse{
			StatusCode: -1,
			StatusMsg:  "User exists",
			UserId:     0,
			Token:      "",
		}, nil
	} else {
		// Error handle
		fmt.Println("Error:", err)
	}
	return
}

// Login implements the UsersrvImpl interface.
func (s *UsersrvImpl) Login(ctx context.Context, req *user.UserLoginRequest) (resp *user.UserLoginResponse, err error) {
	// TODO: Your code here...
	username := req.Username
	password := req.Password

	uid, err := dao.Login(username, password)
	println(uid)
	if uid >= 0 && err == nil {
		TOKEN := username + password
		return &user.UserLoginResponse{
			StatusCode: 0,
			StatusMsg:  "",
			UserId:     uid,
			Token:      TOKEN,
		}, nil
	} else if uid == -1 {
		return &user.UserLoginResponse{
			StatusCode: -1,
			StatusMsg:  "Login failed",
			UserId:     0,
			Token:      "",
		}, nil
	} else {
		// Error handle
		fmt.Println("Error:", err)
	}

	return
}
